//
//  UIImage+Extension.swift
//  MyMicroblog
//
//  Created by Mac on 17/1/11.
//  Copyright © 2017年 itcast. All rights reserved.
//

import UIKit

extension UIImage {

    class func snapShotCurrentWindow() -> UIImage {
        // 获取屏幕信息
        let window = UIApplication.shared.keyWindow
        // 开启图片上下文
        UIGraphicsBeginImageContextWithOptions((window?.bounds.size)!, false, 0)
        // 将 window 绘制到图片上下文
        window?.drawHierarchy(in: (window?.frame)!, afterScreenUpdates: true)
        // 获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        // 关闭图片上下文
        UIGraphicsEndImageContext()
        // 返回图片信息
        return image!
    }
    
    // 缩放图片到指定的宽度
    func scaleImage(Width: CGFloat) -> UIImage {
        let imageWidth = self.size.width
        let imageHeight = self.size.height
        if (imageWidth < Width) {
            return self
        }
        
        let scaleHeight = imageHeight / imageWidth * Width
        let imageBounds = CGRect(x: 0, y: 0, width: Width, height: scaleHeight)
        
        // 开启图片上下文
        UIGraphicsBeginImageContext(imageBounds.size)
        // 将图片绘制到上下文中
        self.draw(in: imageBounds)
        // 获取上下文图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        // 关闭图片上下文
        UIGraphicsEndImageContext()
        
        return image!
    }
    
}
